﻿
namespace Patterns4Net.ArchitectureExplorer.ViewModels
{
    using System.Collections.ObjectModel;
    using System.ComponentModel.Composition;
    using System.Diagnostics.Contracts;
    using Caliburn.Micro;
    using Patterns4Net.ArchitectureExplorer.Diagram;
    using Patterns4Net.ArchitectureExplorer.Infrastructure;
    using Patterns4Net.ArchitectureExplorer.ViewModels.Messages;

    [Export(typeof(ErrorsWindowViewModel))]
    [PartCreationPolicy(CreationPolicy.Shared)]
    public class ErrorsWindowViewModel
    {
        private readonly IDispatcher dispatcher;

        private readonly IEventAggregator eventAggregator;

        [ImportingConstructor]
        public ErrorsWindowViewModel(
            IDispatcher dispatcher,
            IEventAggregator eventAggregator)
        {
            this.dispatcher = dispatcher;
            this.eventAggregator = eventAggregator;
            this.Errors = new ObservableCollection<ErrorViewModel>();
        }

        public ObservableCollection<ErrorViewModel> Errors { get; private set; }

        public ErrorViewModel SelectedError { get; set; }

        public void DoubleClick()
        {
            if (this.SelectedError != null && this.SelectedError.DiagramElement != null)
            {
                this.eventAggregator.Publish(new ZoomToDiagramElementMessage(this.SelectedError.DiagramElement));                
            }
        }

        /// <summary>
        /// Adds given error. 
        /// This method runs the operation in dispatcher thread.
        /// </summary>
        /// <param name="error"></param>
        public void AddError(ErrorViewModel error)
        {
            Contract.Requires(error != null);
            this.dispatcher.BeginInvoke(() => this.Errors.Add(error));
        }

        public void Clear()
        {
            this.dispatcher.BeginInvoke(() => this.Errors.Clear());
        }
    }

    public class ErrorViewModel
    {
        public string TypeName { get; set; }

        public string MethodName { get; set; }

        public string PatternName { get; set; }

        public string ErrorMessage { get; set; }

        public DiagramElement DiagramElement { get; set; }
    }
}
